﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace Duo1JHttpServer.Framework.Utils
{
    /// <summary>
    /// .property配置文件解析
    /// </summary>
    public class Property
    {
        private readonly Dictionary<string, string> dic;

        private static readonly Regex PropertyPattern = new Regex("\\w+(\\.\\w+)*\\s*=\\s*([\"']\\w+[\"'])?(\\w+)?");
        private static readonly Regex StringPattern = new Regex("[\"'].+[\"']");

        /// <summary>
        /// 加载并解析.property配置文件
        /// </summary>
        /// <param name="path">.property文件路径</param>
        public Property(string path)
        {
            dic = new Dictionary<string, string>();

            try
            {
                AnalyzeProperty(path);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        private void AnalyzeProperty(string path)
        {
            byte[] res = IOUtils.ReadFileAll(path);
            if (res != null && res.Length > 0)
            {
                string config = System.Text.Encoding.UTF8.GetString(res);
                string[] linedConfig = config.Split('\n');
                foreach (string line in linedConfig)
                {
                    if (PropertyPattern.IsMatch(line))
                    {
                        string noSpaceLine = line.Replace(" ", "");
                        if (line.StartsWith('#') || line.StartsWith('?'))
                        {
                            continue;
                        }

                        string[] splited = noSpaceLine.Split('=');
                        if (splited.Length != 2 || splited[0] == null || splited[1] == null)
                        {
                            ConsoleUtils.WriteRedLine($"Field does not meet the rules: {noSpaceLine}");
                            continue;
                        }

                        if (StringPattern.IsMatch(splited[1]))
                        {
                            splited[1] = splited[1].Replace("\"", "").Replace("'", "");
                            splited[1] = Convert.ToString(splited[1]);
                        }

                        this[splited[0].ToLower()] = splited[1];
                    }
                    else
                    {
                        ConsoleUtils.WriteRedLine($"Field does not meet the rules: {line}");
                    }
                }
            }
        }

        public string this[string key]
        {
            get { return dic[key]; }
            private set
            {
                if (dic.TryGetValue(key, out string v))
                {
                    ConsoleUtils.WriteRedLine($"Already exist key: {key} - value: {v}");
                }
                else
                {
                    dic.Add(key, value);
                }
            }
        }

        /// <summary>
        /// 尝试获取value
        /// </summary>
        public bool TryGetValue(string key, out string value)
        {
            return dic.TryGetValue(key, out value);
        }

        /// <summary>
        /// 打印所有键值对
        /// </summary>
        public void PrintAll()
        {
            foreach (KeyValuePair<string, string> pair in dic)
            {
                ConsoleUtils.WriteTabLine($"{pair.Key}:{pair.Value}");
            }
        }
    }
}